<template>
  <div class="room" v-show="isShow">
    <audio id="bgAudio" src="../../static/bg_music.mp3" loop></audio>
    <div id="video_area" class="video_area" :style="{height: videoAreaHeight+'rem'}">
      <canvas id="front_camera" class="main_camera" workers="true" render="true" webgl="auto" width="600" height="480" v-show="position == 'front'"
              :style="{opacity: opacity, transform: 'scale(' + videoScale + ',' + videoScale + ') rotate(90deg)'}"></canvas>
      <canvas id="side_camera" class="main_camera" workers="true" render="true" webgl="auto" width="600" height="480" v-show="position == 'side'"
              :style="{opacity: opacity, transform: 'scale(' + videoScale + ',' + videoScale + ') rotate(90deg)'}"></canvas>
      <!-- <div class="video-player" v-if="!isPlaying" style="position: absolute;top:0;left:0;width:100%;height:100%;">
        <div id="lvb" class="lvb" ref="lvb" style="transform: scale(1.34, 1.34) rotate(90deg);width: 100%;height: 100%;"></div>
      </div> -->
      <!--切换视图-->
      <div class="video-camera" @touchstart="checkoutVision"></div>
      <!-- 声音开关 -->
      <div :class="[bgVoiceOpen?'voiceSwitchOpen':'voiceSwitchClose']" @touchstart="voiceSwitch"></div>
      <!-- 游戏时间倒计时 -->
      <div class="timebox" v-if="isPlaying">{{time}}</div>
    </div>
    <div v-if="!isPlaying" class="operate-area">
      <div class="btn_msg" @click="showDollDetail"></div>
      <div v-if="!isOrderGame" class="btn_start" @touchstart="playGame" :class="{btn_order: device_status == 1}">
        {{doll_coin}}金币/次
      </div>
      <div v-else class="order-wait" @touchstart="orderCancel"></div>
      <div>
        <div class="btn_charge" @touchstart="recharge">
          {{userInfo.coin}}
        </div>
      </div>
    </div>
    <div v-if="isPlaying" class="operate-area">
      <div class="ctrlbox">
        <!-- <div v-if="isPlaying" id="nipple" rel="nipple" class="nipple"></div> -->
        <span class="left" @touchstart="moveAction('left', $event)" @touchend="actionMove('55')"></span>
        <span class="right" @touchstart="moveAction('right', $event)" @touchend="actionMove('55')"></span>
        <span class="up" @touchstart="moveAction('up', $event)" @touchend="actionMove('55')"></span>
        <span class="down" @touchstart="moveAction('down', $event)" @touchend="actionMove('55')"></span>
      </div>
      <div v-if="hasCatched" class="catcher_btn"></div>
      <div v-else class="catcher_btn" @touchstart="actionMove('5')"></div>
    </div>

    <!-- Ready go -->
    <div v-if="gamePrepare" class="coverDiv">
      <div class="gamePrepare"></div>
    </div>

    <!-- 预约排位轮到我 -->
    <div v-if="gameStartWait" class="gameStartWaitCover">
      <div class="gameStartWaitPic"></div>
      <div class="gameStartBtn" @click="startPlayGame">
        进入游戏
      </div>
      <div class="gameStartWaitTips">
        {{gameStartWaitTime}}秒内不开始游戏自动退出哦
      </div>
    </div>

    <!-- 金额不够 -->
    <mt-popup
      v-model="lessCoin" :modal="true" :closeOnClickModal="false">
      <div class="inner less-coin">
        <div class="next-btn left" @click="closeCoinModal">先围观</div>
        <div class="next-btn right" @click="recharge">去充值</div>
      </div>
    </mt-popup>

    <!--没抓到模态框-->
    <mt-popup
      v-model="failModal" :modal="true" :closeOnClickModal="false">
      <div class="inner fail">
        <div class="next-btn left" @touchstart="playCancel">休息一下</div>
        <div class="next-btn right" @touchstart="playAgain">再抓一次({{gameStartWaitTime}})</div>
      </div>
    </mt-popup>

    <!--抓到模态框-->
    <mt-popup
      v-model="successModal" :modal="true" :closeOnClickModal="false">
      <div class="inner success">
        <div class="next-btn left" @touchstart="playAgain">继续抓({{gameStartWaitTime}})</div>
        <div class="next-btn right" @touchstart="getAward">去领取</div>
      </div>
    </mt-popup>

    <!-- 围观 -->
    <member ref="member" :doll="doll_id" @play="turnYouPlayGame" @statusChange="deviceStautsChange" @result="checkResult"></member>

    <!--充娃娃币模态框-->
    <recharge :show-recharge="showRecharge" source-class="room" @cancel="hide" @success="updateCoinAccount"></recharge>
    <!-- 查看详情 -->
    <detail :image="detail_image" :show="detail_show" @cancelDetail="hide" :id="doll_id"></detail>
  </div><!--.roomIos-->
</template>
<script type="text/ecmascript-6">
  import api from '@/assets/js/api';//接口API
  // require('@/assets/js/nipplejs.min'); //操作杆；
  import {Toast} from 'mint-ui'; //提示
  import Member from "@/components/member";
  import Detail from "@/components/doll-detail";
  import Recharge from "@/components/recharge";
  import {updateAccount} from '@/assets/js/utils';//接口API
  import {userInfo} from '@/assets/js/utils';//接口API
  import {systemConfig} from '@/assets/js/utils';//接口API
  export default {
    components: {
      Member,
      Detail,
      Recharge
    },
    props: ["roomInfo", "show"],
    data: function () {
      return {
        device_id: '',
        room_id: '',
        action: '',
        isPlaying: false,
        position: 'front',
        opacity: 0,
        userInfo: {},  //用户信息
        //娃娃机信息
        room_id: '', //房间ID
        doll_name: '', //产品名称；
        videoSig: '',
        // doll_id: this.$route.params.device_id, //娃娃机ID；
        device_status: '', //设备状态
        detail_image: '',
        detail_show: false,
        game_mode: '', //游戏模式
        doll_coin: '', //一次消耗币数；
        device_image: '', //设备图片；
        ware_image: '', //产品图片；
        cameras: {}, //摄像头参数
        //(备：cameras_id:摄像头ID,cameras_type:摄像头类型/角度（正面or反面）,cameras_live_openid://摄像头的直播 openid)

        //开始游戏；
        game_id: '', //游戏游戏ID;
        log_id: '', //操作记录ID;
        ws: null,
        coinsList: null, //充值列表
        action: '',
        time: 20,
        angle: 0,
        nipple: null,
        quitRoom: false,
        showStreamVideo: false,
        isGameing: false, //是否操作中；
        rechargeModal: false,
        failModal: false,
        successModal: false,
        lessCoin: false,
        hasCatched: true,
        showRecharge: false,
        list: null,
        stime:null,

        isOrderGame: false,  //是否预约游戏
        gamePrepare: false,  //游戏开始准备
        gameStartWait: false, //等待进入游戏
        gameStartWaitTime: 5, //等待时间
        bgVoiceOpen: false,    //打开背景音乐
        transformVisionTimes: 10, //视角切换次数
        canExitRoom: true,   //是否可以退出房间
        videoAreaHeight: 8.7,   //视频流高度
        videoScale: 1.34,    //视频放大倍数
      }
    },
    computed: {
      doll_id () {
        return this.device_id;
      },
      isShow () {
        return this.show;
      }
    },
    created: function () {
      this.videoAreaHeight = 7.5 * document.body.clientHeight / document.body.clientWidth - 3.4;
      if (this.videoAreaHeight > 8.78) {
        this.videoScale = this.videoScale * this.videoAreaHeight / 8.78;
      }

      //防止游戏中退出房间
      history.pushState(null, null, document.URL);
      window.addEventListener('popstate', () => {
        if (this.isShow) {
          history.pushState(null, null, document.URL);
          if (!this.canExitRoom) {
            Toast('游戏中，请勿退出！');
          } else {
            if (this.needReLoad) {
              //由于ios手机锁屏之后css的animation会失效，目前只能采取重载的方法解决
              window.location.reload();
            } else {
              this.setClose();
            }
          }
        }
      });
    },
    mounted: function () {
      systemConfig(config => {
        this.config = config;
      })
    },
    watch: {
      isShow (val) {
        if (val) {
//          this.position = 'front';
//
//          //初始化房间视频流信息
//          this.userInfo = userInfo();
//          this.device_id = this.roomInfo.id;  //设备id
//          this.room_id = this.roomInfo.room_id; //房间id；
//          this.videoSig = this.roomInfo.qcloud_sig;
//          var cameras = this.roomInfo.cameras;
//          this.cameras = {};
//          for (let i in cameras) {
//            if (cameras[i].type == "front") {
//              this.cameras.frontv = cameras[i].live_openid;
//              this.cameras.hlsfront = cameras[i].hls_address;
//            } else {
//              this.cameras.sidev = cameras[i].live_openid;
//              this.cameras.hlsside = cameras[i].hls_address;
//            }
//          }
//          //获取视频加密签名
////          this.getLookStream(this.cameras.hlsfront);
//          this.initGameScreen(() => {
//            this.opacity = 1;
//          });
//          this.getDollInfo(); //娃娃机信息；
//          this.turnYouPlayGame();
        }
      },
      isPlaying(val) {
        this.transformVisionTimes = 10;  //只能切换10次视角
        if (val) {
//          this.closeLookStream();
          var self = this;
          // if (this.nipple) {
          //   this.nippleDestroy()
          // }
          // setTimeout(() => {
          //   self.nipple = nipplejs.create({
          //     zone: document.getElementById('nipple'),
          //     mode: 'static',
          //     position: {left: '50%', top: '50%'},
          //     color: 'red',
          //     maxNumberOfNipples: 1,
          //     multitouch: false,
          //   });
          //   self.nipple.on('start end', function (evt, data) {
          //     if (evt.type === 'end') {
          //       self.actionMove("55");
          //     }
          //   }).on('dir:up dir:left dir:down dir:right',
          //     function (evt, data) {
          //       if (evt.type.indexOf('dir') !== -1) {
          //         var dir = evt.type.replace("dir:", "");
          //         if (self.position == 'front') {
          //           if (dir == 'up') {
          //             self.actionMove("2");
          //           } else if (dir == 'down') {
          //             self.actionMove("1");
          //           } else if (dir == 'left') {
          //             self.actionMove("3");
          //           } else if (dir == 'right') {
          //             self.actionMove("4");
          //           }
          //         } else {
          //           if (dir == 'up') {
          //             self.actionMove("3");
          //           } else if (dir == 'down') {
          //             self.actionMove("4");
          //           } else if (dir == 'left') {
          //             self.actionMove("1");
          //           } else if (dir == 'right') {
          //             self.actionMove("2");
          //           }
          //         }
          //       }
          //     });
          // }, 50)
        } else {
//          this.getLookStream(this.cameras.hlsfront);
//          if (this.nipple) {
//            this.nippleDestroy()
//          }
        }
      }
    },
    methods: {
      initRoom(roomInfo) {
        this.position = 'front';

        //初始化房间视频流信息
        this.userInfo = userInfo();
        this.device_id = roomInfo.id;  //设备id
        this.room_id = roomInfo.room_id; //房间id；
        this.videoSig = roomInfo.qcloud_sig;
        var cameras = roomInfo.cameras;
        this.cameras = {};
        for (let i in cameras) {
          if (cameras[i].type == "front") {
            this.cameras.frontv = cameras[i].live_openid;
            this.cameras.hlsfront = cameras[i].hls_address;
          } else {
            this.cameras.sidev = cameras[i].live_openid;
            this.cameras.hlsside = cameras[i].hls_address;
          }
        }
        //获取视频加密签名
//          this.getLookStream(this.cameras.hlsfront);
        this.initGameScreen(() => {
          this.opacity = 1;
        });
        this.getDollInfo(); //娃娃机信息；
      },
      setClose () {
        this.closeLookStream();
        this.destroyGameScreen();  //关闭视频流
        this.closeBgVoice(); //关闭背景音乐
        if (this.$refs.member) {
          this.$refs.member.exit();  //退出房间频道
        }
        this.orderCancel();  //取消预约
        if (this.nipple) {  //销毁操作轮盘
          this.nippleDestroy()
        }
        if (this.isPlaying) {   //结束游戏
          this.actionMove(5);  //直接抓取
          this.isPlaying = false;
        }
        this.opacity = 0;
        this.$emit('close');
      },
      getDollInfo() { //娃娃机详情
        api.fetch('/api/machines/' + this.doll_id).then((res) => {
          let dollInfo = res.data;
          this.detail_image = dollInfo.detail_image;
          this.doll_name = dollInfo.name; //产品名称；
          this.device_status = dollInfo.device_status; //设备状态
          this.game_mode = dollInfo.game_mode; //游戏模式
          this.doll_coin = dollInfo.coin; //一次消耗币数；
          this.device_image = dollInfo.device_image; //设备图片；
          this.ware_image = dollInfo.ware_image; //产品图片；
          this.videoSig = dollInfo.qcloud_sig; //视频加密签名
          this.$refs.member.enter(dollInfo.player, dollInfo.device_status);
        }).catch();
      },
      showDollDetail () {
        this.detail_show = true;
      },
      getLookStream(url) {
        this.closeLookStream();
        if (document.getElementById('lvb')) {
          this.player = new TcPlayer("lvb", {
            m3u8: url,
            autoplay: true, //iOS下safari浏览器是不开放这个能力的
            width: "100%",
            height: "100%",
            wording: {
              2032: "请求视频失败，请检查网络",
              2048: "请求m3u8文件失败，可能是网络错误或者跨域问题"
            },
            controls: "none",
          });
        } else {
          setTimeout(() => {
            this.getLookStream(url);
          }, 200);
        }
      },
      closeLookStream() {
        if (this.player) {
          this.player.destroy();
          this.player = null;
        }
      },
      setPlay() {
        if (this.player) {
          this.player.play();
        } else {
          setTimeout(() => {
            this.setPlay();
          }, 200);
        }
      },
      /**
       * 播放背景音乐
       */
      playBgVoice: function () {
        document.getElementById('bgAudio').currentTime = 0;
        document.getElementById('bgAudio').play();
        this.bgVoiceOpen = true;
      },
      /**
       * 关闭背景音乐
       */
      closeBgVoice: function () {
        document.getElementById('bgAudio').pause();
        this.bgVoiceOpen = false;
      },
      /**
       * 继续背景音乐
       */
      continueBgVoice: function () {
        this.needReLoad = true;
        if (this.bgVoiceOpen) {
          document.getElementById('bgAudio').play();
        }
      },
      /**
       * 停止背景音乐
       */
      stopBgVoice: function () {
        document.getElementById('bgAudio').pause();
      },
      hide: function () {
        this.detail_show = false;
        this.showRecharge = false;
      },
      pay(payid) { //支付
        let that=this;
        if (this.config.fake_pay == true) { //模拟支付
          api.fetch('/api/payments/fake-pay', {method: 'POST', data: {'coin_id': payid}}).then((res) => { //充值列表
            api.fetch('/api/payments/' + res.data.id).then((resreset) => {
              Toast("支付成功")
            }).catch();
          }).catch();
        } else { //真实支付
          api.fetch('/api/payments', {method: 'POST', data: {'coin_id': payid}}).then((res) => { //充值列表
            let buyId=res.data.id
            api.fetch('/api/payments/'+buyId+'/prepay-params').then((payres) => {
              //充值发起
              let payInfo=payres.data;
              if (typeof WeixinJSBridge == "undefined") {
                this.coins=res.data.coins;
                if (document.addEventListener) {
                  document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                  document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                  document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
              } else {
                this.onBridgeReady(payInfo,that);
              }
            })
          }).catch();
        }
      },
      onBridgeReady(payInfo, that) { //微信支付
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
            "appId": payInfo.appId,     //公众号名称，由商户传入
            "timeStamp": payInfo.timestamp,         //时间戳，自1970年以来的秒数
            "nonceStr": payInfo.nonceStr, //随机串
            "package": payInfo.package,
            "signType": payInfo.signType,         //微信签名方式：
            "paySign": payInfo.paySign //微信签名
          },
          function (res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              that.showRecharge=false;
              updateAccount(() => {
                that.userInfo = userInfo();
              });
            }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
          });
      },
      updateCoinAccount () {
        updateAccount(() => {
          this.userInfo = userInfo();
          this.hide();
        });
      },
      recharge: function () {
        this.lessCoin = false;
        api.fetch('/api/coins').then((res) => { //娃娃币列表
          this.list = res.data
          this.showRecharge = true;
        }).catch();
      },
      closeCoinModal () {
        this.lessCoin = false;
      },
      /**
       * 轮到你玩游戏了
       */
      turnYouPlayGame: function () {
        if (!this.gameStartWait) {
          this.gameStartWait = true;
          this.gameStartWaitTime = 5;
          this.gameStartWaitInterval = setInterval(() => {
            if (this.gameStartWaitTime == 0) {
              this.gameStartWait = false;
              this.orderCancel();
              clearInterval(this.gameStartWaitInterval);
            } else {
              this.gameStartWaitTime--;
            }
          }, 1000);
        }
      },
      /**
       * 设备状态改变
       */
      deviceStautsChange(e) {
        this.device_status = e.device_status;
      },
      /**
       * 轮到你玩游戏了--进入游戏
       */
      startPlayGame: function () {
        this.gameStartWait = false;
        clearInterval(this.gameStartWaitInterval);
        this.playGame();
      },
      /**
       * 玩游戏
       */
      playGame: function (e) {
        let that=this;
        this.successModal = false;
        this.failModal = false;
        if (!this.isGameing) {
          this.isGameing = true;
          setTimeout(() => {
            this.isGameing = false;
          }, 2000);
          if (this.userInfo.coin >= this.doll_coin) { //是否足够娃娃币
            api.fetch('/api/game-records', {method: 'POST', data: {'machine_id': this.doll_id}}).then((res) => {
              if (res.code == 0) {
                this.isPlaying = true;
                this.canExitRoom = false;
                this.gameStart();
                let gameStartInfo = res.data;
                //进入预约队列
                this.$refs.member.gameReservation(gameStartInfo.id);
                //拉取直播画面
//                this.initGameScreen(() => {
                  //连接娃娃机操作
                  this.ws = new WebSocket(res.data.assign_info.ws_url);
                  //初始化游戏信息
                  this.time = parseInt(gameStartInfo.assign_info.time);
                  this.game_id = gameStartInfo.id; //游戏记录ID
                  this.log_id = gameStartInfo.log_id; //操作记录ID；
                  //倒数3秒钟，开始游戏
                  var waitTime = 3;
                  this.gamePrepare = true;
                  var waitFunc = setInterval(() => {
                    if (waitTime == 0) {
                      this.gamePrepare = false;
                      clearInterval(waitFunc);
//                      this.gameStart();
                    } else {
                      waitTime--;
                    }
                  }, 1000);
//                }, err => {
//                  Toast('无法获取游戏画面');
//                });
              } else if (res.code == 1001) {   //游戏币不足
                this.lessCoin = true;
                this.playCancel();
              } else if (res.code == 1002) {   //有人在玩
                this.isOrderGame = true;
                this.$refs.member.gameReservation();
              }
            }).catch(function (err, res) { //错误信息抓取
              let msg = err.response.data.message;
              Toast(msg);
            });
          }else{
            this.lessCoin = true;
            this.playCancel();
          }
        }
      },
      /**
       * 初始化游戏画面
       */
      initGameScreen: function (success, fail) {
        if (this.gameScreenReady) {
          typeof success == 'function' && success();
          return;
        }
        this.clearCanvas();
        let frontCanvas = document.getElementById("front_camera");
        let sideCanvas = document.getElementById("side_camera");
        TXWawaVideo.init({
          sdkappid: this.config.qcloud.app_id,          //应用的sdkappid
          accounttype: this.config.qcloud.account_type, //账户类型
          roomId: this.room_id,                  //房间ID
          identifier: this.userInfo.live_openid,         //直播openid
          usersig: this.userInfo.qcloud_sig,         //腾讯云签名；
          front: this.cameras.frontv, //正反面
          side: this.cameras.sidev,   //正方面
          sig: this.videoSig,  //视频加密签名
          ver: 2   //版本号
        }, (res) => {
          this.gameScreenReady = true;
          //这里负责渲染视频
          TXWawaVideo.renderVideo([frontCanvas, sideCanvas], () => {
            console.log('渲染视频成功');
            typeof success == 'function' && success();
          });
        }, function (err) {
          console.log(err)
          TXWawaVideo.destroy();
          typeof fail == 'function' && fail();
        })
//        let frontCanvas = document.getElementById("front_camera");
//        let sideCanvas = document.getElementById("side_camera");
//        TXWawaVideo.init({
//          sdkappid: this.config.qcloud.app_id,          //应用的sdkappid
//          accounttype: this.config.qcloud.account_type, //账户类型
//          roomId: this.room_id,                  //房间ID
//          identifier: this.userInfo.live_openid,         //直播openid
//          usersig: this.userInfo.qcloud_sig,         //腾讯云签名；
//          front: this.cameras.frontv, //正反面
//          side: this.cameras.sidev,   //正方面
//          sig: this.videoSig,  //视频加密签名
//          ver: 2   //版本号
//        }, (res) => {
//          this.gameScreenReady = true;
//          //这里负责渲染视频
//          TXWawaVideo.renderVideo([frontCanvas, sideCanvas], () => {
//            console.log('渲染视频成功');
//            typeof success == 'function' && success();
//          });
//        }, function (err) {console.log(err)
//          TXWawaVideo.destroy();
//          typeof fail == 'function' && fail();
//        })
      },
      /**
       * 销毁游戏画面
       */
      destroyGameScreen: function () {
        if (this.gameScreenReady) {
          this.gameScreenReady = false;
          TXWawaVideo.destroy();
        }
      },
      clearCanvas () {
        var c1 = document.getElementById("front_camera");
        var c2 = document.getElementById("side_camera");
        var cxt1 = c1.getContext("webgl");
        var cxt2 = c2.getContext("webgl");
        cxt1.clearColor(0.0, 0.0, 0.0, 1.0);
        cxt1.clear(cxt1.COLOR_BUFFER_BIT);
        cxt2.clearColor(0.0, 0.0, 0.0, 1.0);
        cxt2.clear(cxt1.COLOR_BUFFER_BIT);
      },
      orderCancel: function (e) {
        this.isOrderGame = false;
        this.$refs.member.gameReservationCancel();
      },
      gameStart: function () {
        this.position = 'front';
        this.isOrderGame = false;
        this.hasCatched = false;
        this.opacity = 1;
        this.timeCountDown();
      },
      timeCountDown: function () {
        setTimeout(() => {
          var time = this.time;
          if (time == 0) {
            this.actionMove(5);
          } else {
            if (!this.hasCatched) {
              this.time = this.time - 1;
              this.timeCountDown();
            }
          }
        }, 1000)
      },
      checkResult: function (e) {
        this.position = 'front';
        var operate_result = e.operate_result;
        this.ws.close();
        switch (operate_result + '') {
          case "1":
            this.successModal = true;
            break;
          case "2":
            this.failModal = true;
            break;
        }
        this.againtimeCountDown();
        updateAccount(() => {
          this.userInfo = userInfo();
        });
      },
      againtimeCountDown(){
        this.gameStartWaitTime = 5;
        this.stime = setInterval(() => {
          if (this.gameStartWaitTime == 0) {
            this.playCancel();
          } else {
            this.gameStartWaitTime--;
          }
        }, 1000);
      },
      /**
       * 再玩一次
       */
      playAgain: function () {
        if (this.stime) {
          clearInterval(this.stime);
        }
        this.playGame();
      },
      /**
       * 休息一下
       */
      playCancel: function () {
        if (this.stime) {
          clearInterval(this.stime);
        }
        this.successModal = false;
        this.failModal = false;
        this.isPlaying = false;  //退出游戏状态
//        this.destroyGameScreen(); //销毁游戏画面
        this.orderCancel(); //取消预约
      },
      /**
       * 领取奖励
       */
      getAward: function () {
        this.playCancel();
        this.$router.push("/mywawa");
      },
      moveAction (dir, e) {
        let self = this;
        if (self.position == 'front') {
          if (dir == 'up') {
            self.actionMove("2");
          } else if (dir == 'down') {
            self.actionMove("1");
          } else if (dir == 'left') {
            self.actionMove("3");
          } else if (dir == 'right') {
            self.actionMove("4");
          }
        } else {
          if (dir == 'up') {
            self.actionMove("3");
          } else if (dir == 'down') {
            self.actionMove("4");
          } else if (dir == 'left') {
            self.actionMove("1");
          } else if (dir == 'right') {
            self.actionMove("2");
          }
        }
        e.preventDefault();
      },
      actionMove: function (action, e) {
        this.action = action;
        if (action == '5') {
          setTimeout(() => {
            this.hasCatched = true;
            this.action = 0;
            this.canExitRoom = true;
          }, 200)
        }
        this.ws.send(JSON.stringify({"type": "Control", "data": action}));
      },
      nippleDestroy: function () { //销毁摇杆
        nipplejs.factory && nipplejs.factory.destroy();
      },
      checkoutVision: function () { //切换角度
//        //设置2秒内只能切换一次视角
//        if (this.transformVision) {
//          return;
//        } else {
//          this.transformVision = true;
//          setTimeout(() => {
//            this.transformVision = false;
//          }, 1000)
//        }
//        //判断切换视角次数
//        if (this.transformVisionTimes > 0) {
//          this.transformVisionTimes--;
//        } else {
//          Toast('切换视角次数过多，需等待10分钟后才能再次切换');
//          if (this.waitTransformVisionFunc) return;
//          this.waitTransformVisionFunc = true;
//          setTimeout(() => {
//            this.transformVisionTimes = 10;
//            this.waitTransformVisionFunc = false;
//          }, 600000)
//          return;
//        }

//        if (!this.isPlaying) {
//          if (this.position == 'front') {
//            this.position = 'side';
//            this.getLookStream(this.cameras.hlsside);
//          } else if (this.position == 'side') {
//            this.position = 'front';
//            this.getLookStream(this.cameras.hlsfront);
//          }
//          this.setPlay();
//        } else {
          if (this.position == 'front') {
            this.position = 'side';
          } else if (this.position == 'side') {
            this.position = 'front';
          }
//        }
      },
      voiceSwitch: function () {
        if (this.bgVoiceOpen) {
          this.closeBgVoice();
        } else {
          this.playBgVoice();
        }
      }
    }
  }
</script>
<style lang="less" rel="stylesheet/less" scoped>
  .vcp-player {
    background: none;
  }

  .room {
    .inner {
      width: 4.6rem;
      height: 4.3rem;
      display: flex;
      align-items: flex-end;
      justify-content: space-between;
      .next-btn {
        width: 1.92rem;
        height: 0.76rem;
        border-radius: 0.08rem;
        text-align: center;
        line-height: 0.76rem;
        font-size: 0.3rem;
        &.left {
          background-color: #7373ff;
          color: #50509a;
        }
        &.right {
          background-color: #ffb52b;
          color: #fff;
        }
      }
    }
    .success {
      background: url("../assets/images/success.png") no-repeat center top;
      background-size: 3.83rem 3.08rem;
    }
    .fail {
      background: url("../assets/images/dall.png") no-repeat center top;
      background-size: 3.83rem 3.08rem;
    }
    .less-coin {
      background: url("../assets/images/less-coin.png") no-repeat center top;
      background-size: 3.83rem 3.08rem;
    }
  }
</style>
<style lang="less" rel="stylesheet/less" scoped>
  @import "../style/public";
  @import "../style/setLess";
  .room {
    width: 100%;
    min-height: 100%;
    background-color: #7373ff;
    position: fixed;
    left: 0;
    top: 0;
    display: flex;
    flex-direction: column;
    z-index: 10000;
  }
  .setcolor{
    color:#999;
  }
  .failbox{
    position:relative;
    background:#ec6464;
    img{
      margin-bottom:0.6rem !important;
    }
    .failtis{color:#fff !important;font-size:0.28rem !important;}
    .dolltit{
      display:inline-block;
      width:1.28rem;
      height:.47rem;
      .bis("../assets/images/dalltit.png");
      position:absolute;
      left:50%;
      margin-left:-.64rem;
      top:-.24rem;
    }
  }
  .jxBtn{
    display: inline-block;
    color:#6c0000 !important;
    line-height:.57rem;
    width:2rem;
    height:.57rem;
    color:#fff;
    .bis("../assets/images/continueBtn.png");
    margin-bottom:.4rem;
  }
  .xxBtn{
    display: inline-block;
    color:#6c0000 !important;
    line-height:.57rem;
    width:2rem;
    height:.57rem;
    color:#fff;
    .bis("../assets/images/rest.png");
    margin-bottom:.4rem;
  }

  .coverDiv {
    position: fixed;
    width: 100%;
    height: 100%;
    top:0;
    left:0;
    /*background-color: rgba(0,0,0,0.3);*/
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .gamePrepare {
    width: 1.89rem;
    height: 0.57rem;
    background-image: url(../../static/assets/img/game_ready.png);
    background-size: contain;
    opacity: 0;
    animation: preparechange 1s;
  }
  @keyframes preparechange {
    0% {width: 1.89rem;height: 0.57rem;background-image: url(../../static/assets/img/game_ready.png);background-size: contain;opacity: 1;}
    50% {width: 3.77rem;height: 1.14rem;background-image: url(../../static/assets/img/game_ready.png);background-size: contain;opacity: 1;}
    51% {width: 2.35rem;height: 1.48rem;background-image: url(../../static/assets/img/game_go.png);background-size: contain;opacity: 1;}
    100% {width: 7.5rem;height: 4.72rem;background-image: url(../../static/assets/img/game_go.png);background-size: contain;opacity: 0;}
  }
  .gameStartWaitCover {
    position: fixed;
    width: 100%;
    height: 100%;
    top:0;
    left:0;
    background-color: rgba(0,0,0,0.3);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .gameStartWaitPic {
    width:5.58rem;
    height: 3.04rem;
    background-image: url('../../static/assets/img/game_start_wait.png');
    background-size: contain;
  }
  .gameStartBtn {
    width:1.92rem;
    height:0.76rem;
    line-height:0.76rem;
    background-color: #ffb52b;
    border-radius: 0.08rem;
    margin-top: 0.7rem;
    font-size: 0.3rem;
    color: #ffffff;
    text-align: center;
  }
  .gameStartWaitTips {
    font-size: 0.24rem;
    color:#ffffff;
    margin-top: 0.28rem;
  }

  .timebox {
    position: absolute;
    right: 0.3rem;
    bottom: .3rem;
    text-align: center;
    font-size: .48rem;
    font-weight: bold;
    color: #fff;
    border-radius: 50%;
    z-index: 10;
  }

  .timebox2 {
    position: absolute;
    left: 0.3rem;
    top: 1.28rem;
    width:0.68rem;
    height:0.68rem;
    line-height: 0.68rem;
    border-radius: 100%;
    background-color: rgba(0,0,0,0.3);
    color: #ffffff;
    font-size:0.48rem;
    text-align: center;
    z-index: 10;
  }

  .video_area {
    position: relative;
    width: 6.9rem;
    height: 8.78rem;
    margin: 0.3rem 0.3rem 0;
    border-radius: 0.2rem;
    display: flex;
    align-items: center;
    overflow: hidden;
    background-color: #5050b2;
    background-image: url('../../static/assets/img/loading1.png');
    background-size: 3rem 2.74rem;
    background-position: center;
    background-repeat: no-repeat;
    animation: bgLoading 1s infinite;
    -webkit-animation:bgLoading 1s infinite; /* Safari 和 Chrome */
  }
  @keyframes bgLoading {
    0% {background-image: url('../../static/assets/img/loading1.png')}
    33% {background-image: url('../../static/assets/img/loading2.png')}
    66% {background-image: url('../../static/assets/img/loading3.png')}
    100% {background-image: url('../../static/assets/img/loading1.png')}
  }

  .video_area:last-child {
    background: #fff !important;
  }

  .main_camera {
    width: 100%;
    transform: scale(1.34, 1.34) rotate(90deg);
    -ms-transform: scale(1.34, 1.34) rotate(90deg);
    -webkit-transform: scale(1.34, 1.34) rotate(90deg);
    border-radius: 0.1rem;
  }

  .video-camera {
    position: absolute;
    right: 0;
    bottom: 3.8rem;
    width: 0.48rem;
    height: 0.4rem;
    z-index: 1000;
    background: #7373ff url('../assets/images/camera.png') no-repeat 0.22rem 0.16rem;
    background-size: 0.48rem 0.4rem;
    padding: 0.16rem 0 0.2rem 0.22rem;
    box-sizing: content-box;
    border-top-left-radius: 0.38rem;
    border-bottom-left-radius: 0.38rem;
  }
  .voiceSwitchOpen {
    position: absolute;
    left: 0.3rem;
    bottom: 0.3rem;
    width: 0.48rem;
    height: 0.42rem;
    z-index: 1000;
    background-image: url('../../static/assets/img/voice_open.png');
    background-size: contain;
  }
  .voiceSwitchClose {
    position: absolute;
    left: 0.3rem;
    bottom: 0.3rem;
    width: 0.5rem;
    height: 0.42rem;
    z-index: 1000;
    background-image: url('../../static/assets/img/voice_close.png');
    background-size: contain;
  }
  .operate-area {
    z-index: 999;
    position: fixed;
    bottom: 0;
    left: 50%;
    width: 7.36rem;
    height: 2.97rem;
    background: url("../assets/images/bottom-bg.png") no-repeat;
    background-size: contain;
    margin-left: -3.68rem;
    display: flex;
    // justify-content: space-around;
    align-items: flex-start;
  }
  .btn_msg {
    width: 1.05rem;
    height: 1.42rem;
    background: url(../../static/assets/img/btn_msg.png) no-repeat;
    background-size: contain;
    margin: 0.66rem 0 0 0.44rem;
  }

  .btn_start {
    position: relative;
    width: 3.68rem;
    height: 1.84rem;
    box-sizing: border-box;
    background-size: contain;
    margin: 0.42rem 0.3rem 0;
    padding: 0.98rem 0 0 1.28rem;
    color: rgb(194, 107, 19);
    background-image: url("../../static/assets/img/btn_start.png");
    &:active {
      background: url("../../static/assets/img/btn_start_act.png") no-repeat;
      background-size: contain;
    }
    &.btn_order {
      background: url("../../static/assets/img/order.png") no-repeat;
      background-size: contain;
      color: rgb(19, 159, 194);
      &:active {
        background: url("../../static/assets/img/order_act.png") no-repeat;
        background-size: contain;
      }
    }
  }
  .order-wait {
    position: relative;
    width: 3.68rem;
    height: 1.84rem;
    box-sizing: border-box;
    background-size: contain;
    margin: 0.42rem 0.3rem 0;
    padding: 0.94rem 0 0 1.28rem;
    color: rgb(194, 107, 19);
    background-image: url("../../static/assets/img/order-wait.png");
  }
  .ctrl-container {

  }
  .btn_charge {
    width: 0.97rem;
    height: 1.43rem;
    margin-top: 0.6rem;
    background-size: cover;
    box-sizing: border-box;
    padding: 1.14rem 0 0 0.64rem;
    color:#fff;
    background-image: url("../../static/assets/img/btn_charge.png");
  }
  .ctrlbox {
    position: absolute;
    width: 2.88rem;
    height: 2.4rem;
    top: 0;
    left: 0.52rem;
    span {
      position: absolute;
      width: 0.96rem;
      height: 0.96rem;
      background-size: contain;
    }
    .left {
      left: 0;
      top: 0.78rem;
      background-image: url(/static/img/left.png);
      &:active {
        background-image: url(/static/img/left-click.png);
      }
    }
    .right {
      right: 0;
      top: 0.78rem;
      background-image: url(/static/img/right.png);
      &:active {
        background-image: url(/static/img/right-click.png);
      }
    }
    .up {
      top: 0.1rem;
      left: 0.96rem;
      background-image: url(/static/img/up.png);
      &:active {
        background-image: url(/static/img/up-click.png);
      }
    }
    .down {
      bottom: 0;
      left: 0.96rem;
      background-image: url(/static/img/down.png);
      &:active {
        background-image: url(/static/img/down-click.png);
      }
    }
  }
  .catcher_btn {
    background: url('../assets/images/comfirm_btn.png') no-repeat center center;
    width: 2.87rem;
    height: 1.92rem;
    background-size: 100% auto;
    position: absolute;
    bottom: 0.8rem;
    right: 0.7rem;
    color: #fff;
    text-align: center;
    line-height: 100px;
    font-size: 18px;
    z-index: 1000;
    &:active {
      background: url('../assets/images/confirm_btn_click.png') no-repeat center center;
      background-size: 100% auto;
    }
  }

  .catcher_btn_click {
    background: url('../assets/images/confirm_btn_click.png') no-repeat center center;
    width: 2.87rem;
    height: 1.92rem;
    background-size: 100% auto;
    position: absolute;
    bottom: 0.8rem;
    right: 0.7rem;
    color: #fff;
    text-align: center;
    line-height: 100px;
    font-size: 18px;
    z-index: 1000;
  }

  .userIcon {
    display: block;
    position: absolute;
    .wh(1.83rem, 2.23rem);
    border: 0.03rem solid #ec6564;
    border-radius: 0 0 .1rem 0;
    top: .0rem;
    left: .0rem;
    overflow: hidden;
    z-index:100;
    .userName {
      .font(.28rem, #fff);
      line-height: .5rem;
      text-align: center;
      background: #a54747;
    }
  }
  .mint-popup {
    background: transparent !important;
  }
</style>
